//
//  MatchFriendViewController.m
//  FootPrint
//
//  Created by 秦 东方 on 3/25/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "MatchFriendViewController.h"
#import "ContactReadTool.h"
#import "ContactModel.h"
#import "LocalPeopleCell.h"

@interface MatchFriendViewController ()

@end

@implementation MatchFriendViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _parser = [[FriendParser alloc]init];
        _parser.phoneCheckDelegate = self;
        _parser.addDelegate = self;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    ContactReadTool * readTool = [ContactReadTool getContactReadTool];
    [readTool reReadContact];
    
    self.dicAllPerson = [[NSMutableDictionary alloc] init];
    self.fpPerson = [NSMutableArray array];
    self.selPerson = [NSMutableArray array];
    self.dicFpPerson = [NSMutableDictionary dictionary];
    
    self.PersonAry = readTool.PersonAry;
    NSMutableArray* arr = [[[NSMutableArray alloc]init] autorelease];
    
    for (ContactModel * contactModel in self.personAry) {
        NSString* name = contactModel.PersonName;
        NSMutableArray* phone = contactModel.PhoneLabelAry;
        for(PhoneAndLabel* phoneLable in phone){
            [arr addObject:phoneLable.phoneNum];
            NSString* fullName = [[[name stringByAppendingString:@"("] stringByAppendingString:phoneLable.phoneLabel] stringByAppendingString:@")"];
            [_dicAllPerson setObject:fullName forKey:phoneLable.phoneNum];
        }
    }
    [_parser phoneNumCheck:arr];
    
    // Do any additional setup after loading the view from its nib.
}


- (void)didFinishNoCheck:(PhoneNoCheckResponseMessage*)result{

    if(result != nil && [result resultCode]==0){
        
        int count = [[result checkResultList]count];
        
        if(count == 0){
        
            [[[iToast makeText:@"您的通讯录中没有足迹用户"] setDuration:2000] show];
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_LOGIN_SUCCESS object:nil];
            return;
        }
        
        for(int i=0; i<count; i++){
            PhoneNoCheckResponseMessage_CheckResult* msg = [result checkResultListAtIndex:i];
            long long userId = [msg userId];
            NSString*  userNum = [msg phone];
            [_dicFpPerson setObject:[NSNumber numberWithInt:userId] forKey:userNum];
            [_fpPerson addObject:userNum];
        }
        [_tableView reloadData];
        
        return;
    }
    //失败，直接进入主界面
    if(_needBack){
        if (self.navigationController.viewControllers.count > 1) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self.navigationController dismissModalViewControllerAnimated:YES];
        }
    } else {
        [[[iToast makeText:@"服务器出错"] setDuration:2000] show];
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_LOGIN_SUCCESS object:nil];
    }
    
    
}
- (void)failNoCheck{
    //失败，直接进入主界面
    [[[iToast makeText:@"服务器出错"] setDuration:2000] show];
    if(_needBack){
        if (self.navigationController.viewControllers.count > 1) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self.navigationController dismissModalViewControllerAnimated:YES];
        }
    } else {
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_LOGIN_SUCCESS object:nil];
    }
}

- (void)didAddByPhone:(PhoneNoCheckResponseMessage*)result{

}
- (void)failAddByPhone{

}

- (void)didAddByUid:(FriendAddResponseMessage*)result{
    if(result != nil && [result resultCode]==0){
    
        [[[iToast makeText:@"已发送申请"] setDuration:2000] show];
        if(_needBack){
            if (self.navigationController.viewControllers.count > 1) {
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [self.navigationController dismissModalViewControllerAnimated:YES];
            }
        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_LOGIN_SUCCESS object:nil];
            return;
        }
    } else {
        [[[iToast makeText:@"服务器出错"] setDuration:2000] show];
        if(_needBack){
            if (self.navigationController.viewControllers.count > 1) {
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [self.navigationController dismissModalViewControllerAnimated:YES];
            }
        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_LOGIN_SUCCESS object:nil];
        }
    }
    
}
- (void)failAddByUid{
     [[[iToast makeText:@"服务器出错"] setDuration:2000] show];
    if(_needBack){
        if (self.navigationController.viewControllers.count > 1) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self.navigationController dismissModalViewControllerAnimated:YES];
        }
    } else {
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_LOGIN_SUCCESS object:nil];
    }
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_fpPerson count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *localSelCellIdentifier = @"localSelCellIdentifier";
    LocalPeopleCell *cell = [tableView dequeueReusableCellWithIdentifier:localSelCellIdentifier];
    if (cell == nil) {
        cell = [[[LocalPeopleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:localSelCellIdentifier] autorelease];
    }
    
    BOOL isSelect = NO;
    NSString* number = [_fpPerson objectAtIndex:indexPath.row];
    NSString* name = [_dicAllPerson objectForKey:number];
    cell.textName.text = name;
    cell.textNumber.text = number;
    for(NSString* selNum in _selPerson){
        if([number isEqualToString:selNum]){
            isSelect = YES;
            break;
        }
    }
    cell.imgSelect.highlighted = isSelect;
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BOOL isSelect = NO;
    NSString* number = [_fpPerson objectAtIndex:indexPath.row];
    NSInteger selIdx = -1;
    for(NSString* selNum in _selPerson){
        selIdx++;
        if([number isEqualToString:selNum]){
            isSelect = YES;
            break;
        }
    }
    if(isSelect && selIdx >= 0){
        [_selPerson removeObjectAtIndex:selIdx];
    } else {
        [_selPerson addObject:number];
    }
    [tableView beginUpdates];
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [tableView endUpdates];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_tableView release];
    [_btnSubmit release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setTableView:nil];
    [self setBtnSubmit:nil];
    [super viewDidUnload];
}
- (IBAction)actionBack:(id)sender {
    
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
}

- (IBAction)actionSubmit:(id)sender {
    
    NSMutableArray* ids = [[[NSMutableArray alloc]init] autorelease];
    for(NSString* phone in _selPerson){
        NSNumber* number = [_dicFpPerson objectForKey:phone];
        [ids addObject:number];
    }
    
    [_parser addFriendByUids:ids myId:[GConfig getUserId]];
}
@end
